var consts = require("const")
/**
 * 获得地理位置(经纬度)
 */
function getLocation(cb) {
    wx.getLocation({
        success: function(res) {
            var weidu = res.latitude // 纬度
            var jingdu = res.longitude // 经度
            cb(true, weidu, jingdu)
        },
        fail: function() {
            cb(false)
        }
    })
}

/**
 * 根据地理位置(经纬度)获得天气数据
 */
function getWeather4location(weidu, jingdu, cb) {
    // 请求天气接口
    wx.request({
        // 此处微信语法与接口语法有冲突， 故只能在此拼接
        url: consts.weatherUrl + "?location="+weidu+":"+jingdu,
        data: {
            key: consts.weatherKey
        },
        header: {
            'Content-Type': 'application/json'
        },
        success: function(res) {
            cb(res.data)
        }
    })
}

/**
 * 请求天气数据
 */
function requestGetWeather(cb) {
    getLocation(function(success, weidu, jingdu) {
    if(success == false) {
        jingdu = 116.46
        weidu = 39.92
    }
    getWeather4location(weidu, jingdu, function(weatherData) {
        cb(weatherData)
    })
    }) 
}

//将时间戳格式化为日期
function formatDate(timestamp) {
    var date = new Date(timestamp * 1000);
    return date.getMonth()+1 + "月" + date.getDate() + "日 " + formatWeekday(timestamp);
}

//将时间戳格式化为时间
function formatTime(timestamp) {
    var date = new Date(timestamp * 1000);
    return date.getHours() + ":" + date.getMinutes();
}

//中文形式的每周日期
function formatWeekday(timestamp) {
    var date = new Date(timestamp * 1000);
    var weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    var index = date.getDay();
    return weekday[index];
}

/**
 * 获得天气(暴露接口)
 */
function getWeather(cb) {
    requestGetWeather(function(data) {
        // 对数据进行修饰  然后返回给前端
        var weatherData = {}
        weatherData = data
        var weather = new Object()
        weather.city = weatherData.results[0].location.name
        var daily = []
        for(var i = 0; i < weatherData.results[0].daily.length; i++) {
            var dailyItem  = weatherData.results[0].daily[i]
            dailyItem["time"] = weatherData.results[0].daily[i].date
            dailyItem["textDay"] = weatherData.results[0].daily[i].text_day
            dailyItem["codeDay"] = weatherData.results[0].daily[i].code_day
            dailyItem["textNight"] = weatherData.results[0].daily[i].text_night
            dailyItem["codeNight"] = weatherData.results[0].daily[i].code_night
            dailyItem["high"] = weatherData.results[0].daily[i].high
            dailyItem["low"] = weatherData.results[0].daily[i].low
            daily.push(dailyItem)
        }
        weather.daily = daily
        cb(weather)
    })
}

module.exports = {
    getWeather: getWeather
}


